﻿
using System;
using System.Collections.Generic;
using EOS.Framework.Web.Mvc.Rendering;

namespace EOS.Framework.Web.Mvc.Controls
{
    public class TemplateControl : Control
    {
        private string template;
        private Dictionary<string, object> values;

        public Dictionary<string, object> Values
        {
            get
            {
                if (values == null)
                {
                    values = new Dictionary<string, object>();
                }
                return values;
            }
            set { values = value; }
        }

        public string Template
        {
            get { return template; }
            set { template = value; }
        }

        public TemplateControl(string template)
        {
            this.template = template;
        }
	
        protected override void OnRender(IXhtmlWriter writer, PageContext context)
        {
            if (string.IsNullOrEmpty(template))
            {
                throw new NotSupportedException(Properties.Resources.InvalidTemplate);
            }

            string output = template;

            int index = 0;
            while (index < template.Length && index != -1)
            {
                int markerIndex = output.IndexOf("#", index);
                if (markerIndex != -1)
                {
                    int end = output.IndexOfAny(new char[] { '"', '<' }, markerIndex);

                    string placeholder = output.Substring(markerIndex, end - markerIndex);

                    if (values.ContainsKey(placeholder.Substring(1)))
                    {
                        output = output.Replace(placeholder, values[placeholder.Substring(1)].ToString());
                    }
                    else
                    {
                        throw new NotSupportedException(Properties.Resources.TemplateValueNotFound);
                    }
                }

                index = markerIndex;
            }

            WriteBeginAttachedTag(writer);
            writer.WriteRaw(output);
            WriteEndAttachedTag(writer);
        }
    }
}
